<template>
  <div class="about">
    <el-button type="primary" @click="showDialog">上传图片</el-button>
    <el-button type="primary" @click="downJson">导出json</el-button>
    <el-button type="primary" @click="exportJson">导入json</el-button>
    <el-button type="primary" @click="downAllImage">下载图片</el-button>
    <el-button type="primary" @click="downSimpleImage">下载图层图片</el-button>
    <div class="canvas-box">
      <canvas id="canvas" width="800" height="500" style="border: 1px solid #ccc;"></canvas>
      <!-- 作为单独图层的容器 -->
      <canvas id="simpleCanvas" width="200" height="200" style="border: 1px solid #ccc;"></canvas>
    </div>
    <el-dialog v-model="isShowDialog" title="上传图片" width="500">
      <div class="upload-wrap">
        <el-upload ref="uploadRef" class="avatar-uploader" :action="uploadImageUrl" name="avatar"
          :show-file-list="false" :auto-upload="false" :on-change="handleUploadChange" :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl2" :src="imageUrl2" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowDialog = false">取消</el-button>
          <el-button type="primary" @click="uploadSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { uploadImageUrl } from '@/api'
import { fabric } from 'fabric'
let canvasCtx, simpleCanvasCtx, canvasCtxJSON = {}
function init() {
  // 初始化画布
  canvasCtx = new fabric.Canvas('canvas', { crossOrigin: 'anonymous' })
  simpleCanvasCtx = new fabric.Canvas('simpleCanvas', { crossOrigin: 'anonymous' })
  // // 创建一个长方形
  // const rect = new fabric.Rect({
  //   top: 30, // 距离容器顶部 30px
  //   left: 30, // 距离容器左侧 30px
  //   width: 100, // 宽 100px
  //   height: 60, // 高 60px
  //   fill: 'red' // 填充 红色
  // })

  fabric.Image.fromURL('https://imgs.bestwehotel.com/images/inn/1gkRHNFC6i', (img) => {
    img.set({
      // 通过scale来设置图片大小，这里设置和画布一样大
      scaleX: canvasCtx.width / img.width,
      scaleY: canvasCtx.height / img.height,
    })
    // 设置背景
    canvasCtx.setBackgroundImage(img, canvasCtx.renderAll.bind(canvasCtx))
    canvasCtx.renderAll()
  }, { crossOrigin: 'anonymous' })

  // 在canvas画布中加入矩形（rect）。add是“添加”的意思
  // canvasCtx.add(rect)

}

const handleUploadChange = (uploadFile) => {
  imageUrl2.value = URL.createObjectURL(uploadFile.raw)
}
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  console.log(response, uploadFile)
  if (response.code === 0) {
    ElMessage.success('上传成功')
    imageUrl.value = response.data.src
    isShowDialog.value = false
    fabric.Image.fromURL(response.data.src, (img) => {
      canvasCtx.add(img)
    }, { crossOrigin: 'anonymous' })
    // fabric.Image.fromURL(response.data.src, (img) => {
    //   simpleCanvasCtx.add(img)
    // }, { crossOrigin: 'anonymous' })
  }

}

const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile)
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('请上传图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('Avatar picture size can not exceed 5MB!')
    return false
  }
  return true
}
const imageUrl = ref('')
const imageUrl2 = ref('')
const uploadRef = ref(null)
const isShowDialog = ref(false)
function uploadSubmit() {
  uploadRef.value.submit()
}
function showDialog() {
  isShowDialog.value = true
  imageUrl2.value = ''
}
function downJson() {
  console.log('canvas stringify ', JSON.stringify(canvasCtx))
  console.log('canvas toJSON', canvasCtx.toJSON())
  console.log('canvas toObject', canvasCtx.toObject())
  canvasCtxJSON = canvasCtx.toJSON()
}
function exportJson() {
  const dataJson = {
    version: canvasCtxJSON.version,
    objects: canvasCtxJSON.objects,
  }
  // 反序列化 导入json
  simpleCanvasCtx.loadFromJSON(JSON.stringify(dataJson))
}
function downAllImage() {
  const dataURL = canvasCtx.toDataURL({
    width: canvasCtx.width,
    height: canvasCtx.height,
    left: 0,
    top: 0,
    format: 'png',
  });
  const link = document.createElement('a');
  link.download = 'canvas.png';
  link.href = dataURL;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
function downSimpleImage() {
  const dataURL = simpleCanvasCtx.toDataURL({
    width: simpleCanvasCtx.width,
    height: simpleCanvasCtx.height,
    left: 0,
    top: 0,
    format: 'png',
  });
  const link = document.createElement('a');
  link.download = 'canvas.png';
  link.href = dataURL;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
onMounted(async () => {
  init()
})
</script>
<style>
.about {
  width: 1200px;
  margin: 0 auto;
  padding-top: 20px;
}

#simpleCanvas {
  /* display: none; */
}
</style>
<style>
.canvas-box {
  display: flex;
  padding-top: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
